const {
  get,
  post
} = require("../../utils/request")
Page({
  data: {
    id: '',
    latitude: '',
    longitude: '',
    price: '',
    scenicSubCounts: '',
    language: 1,
    markers: [],
    isAuto: false,
    isHidden: false,
    list: [],
    markerList: [],
    polyline: [],
    scale: 6,
    routeId: ''
  },

  onLoad: function (options) {
    this.setData({
      id: options.id,
      scenicSubCounts: options.scenicSubCounts,
      price: options.price,
      latitude: options.latitude,
      longitude: options.longitude
    }, () => {
      if (!wx.getStorageSync('phone')) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      } else {
        this.getAllList()
      }
    })
  },
  onShow: function () {
    if (wx.getStorageSync('phone') && this.data.list.length == 0) {
      this.getAllList()
      this.mapCtx = wx.createMapContext("map", this)
      // 创建动画实例
      var animation = wx.createAnimation({
        duration: 400, //动画的持续时间
        timingFunction: 'ease', //动画的效果 默认值是linear->匀速，ease->动画以低速开始，然后加快，在结束前变慢
      })
      this.animation = animation; //将animation变量赋值给当前动画
      setTimeout(() => {
        this.setCenterFn() //设置地图中心点
      }, 140);
      //判断是否已经购买过
      get('/order/checkPurchase', {
        scenicId: this.data.id,
        language: this.data.language
      }).then(res => {
        //返回cnt   1 代码购买了，， 0 是没有购买
        if (res.cnt == 1) {
          this.setData({
            isAuto: true
          })
        } 
      })
    }
  },
  //点击推荐路线
  routeListFn() {
    let that = this;
    get('/route/list', {
      scenicId: this.data.id,
      language: this.data.language
    }).then(res => {
      let arr = []
      res.map(item => {
        arr.push(item.title)
      })
      arr.push('关闭线路')
      wx.showActionSheet({
        itemList: arr,
        success(idx) {
          if (idx.tapIndex == res.length) {
            that.getAllList()
            that.setData({
              polyline: [],
              routeId: ''
            })
          } else {
            get('/route/getRouteInfo', {
              id: res[idx.tapIndex].id,
              language: that.data.language
            }).then(data => {
              let pl = []
              data.map(item => {
                pl.push({
                  latitude: item.latitude,
                  longitude: item.longitude
                })
                item.audioTime = item.audioTime && that.formatTime(item.audioTime) || '未知'
              })
              that.setData({
                routeId: res[idx.tapIndex].id,
                list: data,
                polyline: [{
                  points: pl,
                  color: '#FA681C',
                  width: 3
                }]
              })
            })
          }
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    })
    if (this.innerAudioContext) {
      this.innerAudioContext.stop() // 暂停
    }
  },
  getAllList() {
    //获取弹窗音频列表
    let mks = []
    wx.showLoading({
      title: '加载中,请稍后...',
      mask: true
    })
    get('/scenic/area/getAllScenicAuditList', {
      language: 1,
      scenicId: this.data.id
    }).then(res => {
      res.map(item => {
        item.audioTime = item.audioTime && this.formatTime(item.audioTime) || '未知',
          item.flag = false
        //起点和终点的距离单位km
        mks.push({
          id: item.id,
          latitude: item.latitude,
          longitude: item.longitude,
          iconPath: './../../images/mapicon.png',
          callout: {
            content: item.scenicName,
            display: 'ALWAYS',
            color: "#fff",
            fontSize: 8,
            padding: 4,
            bgColor: '#550000',
            borderRadius: 5
          },
          width: '50rpx',
          height: '50rpx',
          showMoreFlag: false
        })
      })
      this.setData({
        list: res,
        markers: mks
      },()=>{
        wx.hideLoading()
      })
    })
  },
  playOrpauseFn(e) {
    let index = e.currentTarget.dataset.index
    let freeAudio = e.currentTarget.dataset.freeaudio;
    if (!wx.getStorageSync('phone')) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      if (freeAudio == 0) {
        wx.showToast({
          title: '非试听讲解点，请解锁后收听',
          icon: 'none'
        })
      } else {
        if (!!this.data.list[index].flag) {
          this.stopFn()
        } else {
          this.playAudioFn(e)
        }
      }
    }

  },
  // 点击音频列表
  playAudioFn(e) {
    let audiourl = e.currentTarget.dataset.audiourl
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    this.playFn(audiourl, index)
    post('/scenic/area/incPlayCount?id=' + id)
  },

  playFn(audiourl, index) {
    let that = this
    if (this.innerAudioContext) {
      this.innerAudioContext.destroy()
    }
    this.innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false
    })
    this.innerAudioContext.src = audiourl
    this.innerAudioContext.play() // 播放
    let listArr = this.data.list
    this.innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    this.innerAudioContext.onEnded(() => {
      if (this.data.isAuto) {
        console.log('打开自动播放');
        wx.startLocationUpdate({
          success() {
            const _locationChangeFn = function (res) {
              console.log(that.data, '获取经纬度');
              //可以得到经纬度
              get('/scenic/area/getLatestScenic', {
                scenicId: that.data.id,
                longitude: res.longitude,
                latitude: res.latitude,
                language: that.data.language,
                routeId: that.data.routeId || 0
              }).then(res => {
                let index = null
                listArr.map((item, idx) => {
                  if (res.id == item.id) {
                    index = idx
                  }
                })
                that.playFn(res.audioUrl, index)
              })
              wx.offLocationChange(_locationChangeFn)
            }
            wx.onLocationChange(_locationChangeFn)
          },
          fail() {
            console.log('没开定位');
            wx.showToast({
              title: '使用自动播放功能请手动打开定位权限',
              icon: 'none'
            })
          }
        })
      }
      listArr.map(item => {
        item.flag = false
      })
      this.setData({
        list: listArr
      })
    })
    listArr.map(item => {
      item.flag = false
    })
    listArr[index].flag = true
    this.setData({
      list: listArr
    })
  },
  stopFn() {
    this.innerAudioContext.pause() // 暂停
    let listArr = this.data.list
    listArr.map(item => {
      item.flag = false
    })
    this.setData({
      list: listArr
    })
  },

  bindmarkertap(res) {
    // wx.showToast({
    //   title: '点击插件id是'+ res.detail.markerId,
    // })
  },
  questionFn() {
    wx.navigateTo({
      url: '/pages/question/question',
    })
  },
  showMoreFn() {
    var time1 = setTimeout(() => {
      this.slideIn(); //调用动画--滑入
      clearTimeout(time1);
      time1 = null;
      this.setData({
        showMoreFlag: true
      })
    }, 100);
  },
  showLittleFn() {
    this.slideDown()
  },
  //动画 -- 滑入
  slideIn: function () {
    const height = wx.getSystemInfoSync().screenHeight
    this.animation.height(height - 300).step()
    this.setData({
      //动画实例的export方法导出动画数据传递给组件的animation属性
      animationData: this.animation.export()
    })
  },
  //动画 -- 滑出
  slideDown: function () {
    this.animation.height('45vh').step()
    this.setData({
      animationData: this.animation.export(),
      showMoreFlag: false
    })
  },
  //点击是否自动播放
  autoFn() {
    let that = this;
    if (!wx.getStorageSync('phone')) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      get('/order/checkPurchase', {
        scenicId: this.data.id,
        language: this.data.language
      }).then(res => {
        //返回cnt   1 代码购买了，， 0 是没有购买
        if (res.cnt == 1) {
          this.setData({
            isAuto: !this.data.isAuto
          })
        } else {
          wx.showToast({
            title: '您尚未解锁导览讲解，解锁后即可解锁自动播放',
            icon: 'none'
          })
        }
      })
    }
  },
  //点击跳转到景点详情页面
  attractDetailFn(e) {
    let that = this;
    let freeAudio = e.currentTarget.dataset.freeaudio;
    if (!wx.getStorageSync('phone')) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      if (freeAudio == 0) {
        wx.showToast({
          title: '非试听讲解点，请解锁后收听',
          icon: 'none'
        })
      } else {
        wx.navigateTo({
          url: '/pages/attractDetail/attractDetail?id=' + e.currentTarget.dataset.id + '&isAuto=' + this.data.isAuto + '&language=' + this.data.language + '&routeId=' + this.data.routeId,
          events: {
            someEvent: function (data) {
              that.setData({
                latitude: data.lat,
                longitude: data.log
              })
            }
          }
        })
        if (this.innerAudioContext) {
          this.innerAudioContext.stop() // 暂停
        }
        let listArr = this.data.list
        listArr.map(item => {
          item.flag = false
        })
        this.setData({
          list: listArr
        })
      }
    }
  },
  //重新设置中心点
  setCenterFn() {
    console.log(this.data.latitude);
    this.mapCtx.moveToLocation({
      latitude: this.data.latitude,
      longitude: this.data.longitude
    })
  },
  setCenterFn1() {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      success (res) {
      that.mapCtx.moveToLocation({
        latitude: res.latitude,
        longitude: res.longitude
      })
      }
     })
  },
  clickFn() {
    this.setData({
      isHidden: !this.data.isHidden
    })
  },
  formatTime(value) {
    var secondTime = parseInt(value) // 秒
    var minuteTime = 0 // 分
    var result = ''
    if (secondTime < 60) {
      result = '00:' + (secondTime > 9 ? secondTime : '0' + secondTime);
    } else {
      minuteTime = parseInt(secondTime / 60)
      secondTime = parseInt(secondTime % 60)
      let minute = minuteTime > 9 ? minuteTime : '0' + minuteTime;
      let second = secondTime > 9 ? secondTime : '0' + secondTime;
      result = minute + ':' + second;
    }
    return result;
  },
  toBuyFn() {
    let that = this;
    if (!wx.getStorageSync('phone')) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      get('/order/checkPurchase', {
        scenicId: this.data.id,
        language: this.data.language
      }).then(res => {
        //返回cnt   1 代码购买了，， 0 是没有购买
        if (res.cnt == 1) {
          wx.showToast({
            title: '您已经解锁所有的讲解点,无需重复购买',
            icon: 'none'
          })
        } else {
          post('/order/createOrder', {
            shopId: wx.getStorageSync('shopId') || null,
            id: this.data.id
          }).then(res => {
            post('/order/getPrePayParams', {
              id: res.id
            }).then(res => {
              wx.requestPayment({
                nonceStr: res.nonceStr,
                package: res.package,
                paySign: res.paySign,
                signType: res.signType,
                timeStamp: res.timeStamp,
                success: function () {
                  wx.reLaunch({
                    url: '/pages/index/index?scenicId='+ that.data.id,
                  })
                },
                fail: function (fail) {
                  console.log(fail);
                }
              })
            })
          })
        }
      })

    }
  },
  onHide() {
    if (this.innerAudioContext) {
      this.innerAudioContext.stop() // 暂停
    }
    let listArr = this.data.list
    listArr.map(item => {
      item.flag = false
    })
    this.setData({
      list: listArr
    })
  },
  onUnload() {
    if (this.innerAudioContext) {
      this.innerAudioContext.stop() // 暂停
    }
    let listArr = this.data.list
    listArr.map(item => {
      item.flag = false
    })
    this.setData({
      list: listArr
    })
  },
  onShareAppMessage() {
    return {
      title: '一触即听，景行千里',
      imageUrl:'./../../images/share.jpg',
      path: '/pages/index/index?scenicId='+ this.data.id
    }
  }
})